package com.hanxiaozhang.lua;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;


/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/10/10
 * @since 1.0.0
 */
@Component
public class LuaExample {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String LUA_SCRIPT =
            "if redis.call('exists',KEYS[1]) == 0 then" +
            "    redis.call('set',KEYS[1], ARGV[1]);" +
            "    return redis.call('expire',KEYS[1], ARGV[2]);" +
            "else" +
            "    return 2;" +
            "end";

    /**
     * 是否已经被消费
     *
     * @param key
     * @param value
     * @param expireTime 单位：秒
     * @return
     */
    public boolean hasConsume(String key, String value, Integer expireTime) {

        // 封装Lua脚本实体
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_SCRIPT,Long.class);
        // 指定返回类型
        redisScript.setResultType(Long.class);
        // 执行Lua脚本，参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(key), value, String.valueOf(expireTime));
        if (result == 2L) {
            return true;
        }
        return false;
    }

}
